package com.heima.app.gateway.filter;

import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
@Order(-1)
@RefreshScope
public class AuthFilter implements GlobalFilter {
    @Value("${ignoreUrl}")
    private List<String> ignoreUrl;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //解析token看一下过期了没
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();

        //判断该路径是否被忽略
        String path = request.getURI().getPath();
        if(ignoreUrl.contains(path)){
            log.info("请求放行");
            return chain.filter(exchange);
        }

        //获取token
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(token)){
            log.info("token为空");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        Claims body = AppJwtUtil.getClaimsBody(token);
        int flag = AppJwtUtil.verifyToken(body);
        //token过期
        if(flag == 1 || flag == 2){
            log.info("token过期");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //token校验成功
        return chain.filter(exchange);
    }
}
